package com.nodecollege.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.UpmsConstants;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.*;
import com.nodecollege.cloud.common.model.po.*;
import com.nodecollege.cloud.common.model.vo.MenuTreeVO;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.common.utils.RedisUtils;
import com.nodecollege.cloud.dao.mapper.UpmsMemberMapper;
import com.nodecollege.cloud.dao.mapper.UpmsOrgMapper;
import com.nodecollege.cloud.dao.mapper.UpmsRoleMapper;
import com.nodecollege.cloud.dao.mapper.UpmsTenantMapper;
import com.nodecollege.cloud.service.MemberService;
import com.nodecollege.cloud.service.OrgService;
import com.nodecollege.cloud.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LC
 * @date 2019/12/12 15:19
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private UpmsMemberMapper upmsMemberMapper;

    @Autowired
    private UpmsTenantMapper upmsTenantMapper;

    @Autowired
    private UpmsOrgMapper upmsOrgMapper;

    @Autowired
    private UpmsRoleMapper upmsRoleMapper;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 查询成员列表
     *
     * @param queryVO
     * @return
     */
    @Override
    public NCResult<UpmsMember> getMemberList(QueryVO<UpmsMember> queryVO) {
        List<UpmsMember> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(queryVO.getPageSize())) {
            list = upmsMemberMapper.selectListByMap(queryVO.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
            if (queryVO.isSort()) {
                page.setOrderBy(queryVO.getSortKey() + " " + queryVO.getSortDirection());
            }
            list = upmsMemberMapper.selectListByMap(queryVO.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 修改成员列表
     *
     * @param upmsMember
     */
    @Override
    public void updateMember(UpmsMember upmsMember) {
        NCUtils.nullOrEmptyThrow(upmsMember.getMemberId(), new UpmsException("-1", "成员id必填！"));
        NCUtils.nullOrEmptyThrow(upmsMember.getMemberAccount(), new UpmsException("-1", "成员账号必填！"));
        NCUtils.nullOrEmptyThrow(upmsMember.getMemberName(), new UpmsException("-1", "成员名称必填！"));
        UpmsMember exit = upmsMemberMapper.selectByPrimaryKey(upmsMember.getMemberId());
        NCUtils.nullOrEmptyThrow(exit, new UpmsException("-1", "不存在该成员！"));
        if (!exit.getTenantId().equals(upmsMember.getTenantId())) {
            throw new UpmsException("-1", "不存在该成员！");
        }

        UpmsMember exitQuery = new UpmsMember();
        exitQuery.setTenantId(upmsMember.getTenantId());
        exitQuery.setMemberAccount(upmsMember.getMemberAccount());
        List<UpmsMember> exitList = upmsMemberMapper.selectListByMap(new QueryVO<>(exitQuery).toMap());
        if (exitList.size() == 1 && !exitList.get(0).getMemberId().equals(exit.getMemberId())) {
            throw new UpmsException("-1", "该成员账号已存在！");
        }

        exitQuery.setMemberAccount(null);
        exitQuery.setMemberName(upmsMember.getMemberName());
        exitList = upmsMemberMapper.selectListByMap(new QueryVO<>(exitQuery).toMap());
        if (exitList.size() == 1 && !exitList.get(0).getMemberId().equals(exit.getMemberId())) {
            throw new UpmsException("-1", "该成员名称已存在！");
        }

        UpmsMember updateMember = new UpmsMember();
        updateMember.setMemberId(upmsMember.getMemberId());
        updateMember.setMemberName(upmsMember.getMemberName());
        updateMember.setMemberAccount(upmsMember.getMemberAccount());
        upmsMemberMapper.updateByPrimaryKeySelective(updateMember);
    }

    /**
     * 删除成员列表
     *
     * @param upmsMember
     */
    @Override
    public void delMember(UpmsMember upmsMember) {
        NCUtils.nullOrEmptyThrow(upmsMember.getMemberId(), new UpmsException("-1", "成员id必填！"));
        UpmsMember exit = upmsMemberMapper.selectByPrimaryKey(upmsMember.getMemberId());
        NCUtils.nullOrEmptyThrow(exit, new UpmsException("-1", "不存在该成员！"));
        if (!exit.getTenantId().equals(upmsMember.getTenantId())) {
            throw new UpmsException("-1", "不存在该成员！");
        }
        if (exit.getState().equals(NCConstants.INT_0)) {
            throw new UpmsException("-1", "该成员不能删除！");
        }
        UpmsMember delMember = new UpmsMember();
        delMember.setMemberId(upmsMember.getMemberId());
        delMember.setState(NCConstants.INT_NEGATIVE_1);
        upmsMemberMapper.updateByPrimaryKeySelective(delMember);
    }

    /**
     * 锁定解锁成员
     *
     * @param upmsMember
     */
    @Override
    public void lockMember(UpmsMember upmsMember) {
        if (!Arrays.asList(NCConstants.INT_1, NCConstants.INT_2).contains(upmsMember.getState())) {
            throw new UpmsException("", "只能进行冻结或者解冻操作");
        }
        // 根据id查询成员信息
        UpmsMember member = upmsMemberMapper.selectByPrimaryKey(upmsMember.getMemberId());
        NCUtils.nullOrEmptyThrow(member, new UpmsException("-1", "该成员不存在！"));
        if (!member.getTenantId().equals(upmsMember.getTenantId())) {
            throw new UpmsException("-1", "该成员不存在");
        }
        if (NCConstants.INT_0.equals(member.getState())) {
            throw new UpmsException("-1", "该成员不能冻结！");
        }
        UpmsMember lockMember = new UpmsMember();
        lockMember.setMemberId(upmsMember.getMemberId());
        lockMember.setState(upmsMember.getState());
        upmsMemberMapper.updateByPrimaryKeySelective(lockMember);
    }

    /**
     * 更新成员默认信息
     *
     * @param member
     */
    @Override
    public void updateMemberDefaultInfo(UpmsMember member, LoginUser loginUser) {
        NCUtils.nullOrEmptyThrow(member.getMemberId(), new UpmsException("", "成员id必填！"));
        NCUtils.nullOrEmptyThrow(member.getTenantId(), new UpmsException("", "成员租户id必填！"));
        NCUtils.nullOrEmptyThrow(member.getShowAllRole(), new UpmsException("", "是否显示全部角色必填！"));
        NCUtils.nullOrEmptyThrow(member.getShowAllOrg(), new UpmsException("", "是否显示全部组织机构必填！"));
        NCUtils.nullOrEmptyThrow(member.getDefaultRoleId(), new UpmsException("", "默认角色id必填！"));
        NCUtils.nullOrEmptyThrow(member.getDefaultOrgId(), new UpmsException("", "默认组织机构id必填！"));

        if (member.getShowAllRole() != 0 && member.getShowAllRole() != 1) {
            throw new UpmsException("", "是否显示全角色取值有误");
        }

        if (member.getShowAllOrg() != 0 && member.getShowAllOrg() != 1) {
            throw new UpmsException("", "是否显示全组织机构取值有误");
        }

        UpmsMember exMember = upmsMemberMapper.selectByPrimaryKey(member.getMemberId());
        NCUtils.nullOrEmptyThrow(exMember, new UpmsException("", "该成员不存在！"));
        if (!member.getTenantId().equals(exMember.getTenantId())) {
            throw new UpmsException("", "该成员不存在！");
        }

        UpmsMember updateMember = new UpmsMember();
        updateMember.setMemberId(member.getMemberId());
        updateMember.setShowAllRole(member.getShowAllRole());
        updateMember.setShowAllOrg(member.getShowAllOrg());
        updateMember.setDefaultRoleId(member.getDefaultRoleId());
        updateMember.setDefaultOrgId(member.getDefaultOrgId());

        upmsMemberMapper.updateByPrimaryKeySelective(updateMember);

        loginUser.setInfoRandom(NCUtils.getUUID());

        initMemberDataPower(loginUser);

        redisUtils.set(UpmsConstants.USER_LOGIN_INFO + loginUser.getAccessToken(), loginUser, loginUser.getExpire());
    }

    /**
     * 初始化成员数据权限
     *
     * @param loginUser
     */
    @Override
    public void initMemberDataPower(LoginUser loginUser) {
        if (loginUser == null) {
            return;
        }
        Long tenantId = loginUser.getTenantId();
        if (tenantId == null) {
            return;
        }
        // 查询默认租户信息
        UpmsTenant tenant = upmsTenantMapper.selectByPrimaryKey(tenantId);
        if (NCUtils.isNullOrEmpty(tenant)) {
            return;
        }
        loginUser.setTenantName(tenant.getTenantName());
        loginUser.setTenantState(tenant.getState());

        // 查询绑定租户列表
        List<UpmsTenant> tenantList = upmsTenantMapper.selectTenantListByUserId(loginUser.getUserId());
        List<IdName> tenantIdNameList = tenantList
                .stream()
                .map(item -> new IdName(item.getTenantId(), item.getTenantName()))
                .collect(Collectors.toList());
        loginUser.setTenantList(tenantIdNameList);

        if (NCConstants.INT_2.equals(tenant.getState())) {
            // 租户被禁用，直接返回
            return;
        }

        // 查询租户成员信息
        UpmsMember queryMember = new UpmsMember();
        queryMember.setTenantId(tenantId);
        queryMember.setUserId(loginUser.getUserId());
        List<UpmsMember> members = upmsMemberMapper.selectListByMap(new QueryVO<>(queryMember).toMap());
        if (NCUtils.isNullOrEmpty(members)) {
            return;
        }
        UpmsMember member = members.get(0);
        loginUser.setMemberId(member.getMemberId());
        loginUser.setMemberName(member.getMemberName());
        loginUser.setMemberState(member.getState());
        loginUser.setShowAllRole(member.getShowAllRole());
        loginUser.setShowAllOrg(member.getShowAllOrg());
        if (NCConstants.INT_2.equals(member.getState())) {
            // 租户被禁用，直接返回
            return;
        }

        // 查询成员默认组织机构信息
        UpmsOrg org = upmsOrgMapper.selectByPrimaryKey(member.getDefaultOrgId());
        if (org != null) {
            loginUser.setOrgId(org.getOrgId());
            loginUser.setOrgState(org.getState());
        }

        // 查询成员默认角色信息
        UpmsRole role = upmsRoleMapper.selectByPrimaryKey(member.getDefaultRoleId());
        if (role != null) {
            loginUser.setRoleId(role.getRoleId());
            loginUser.setRoleState(role.getState());
        }

        // 查询成员被直接授权的组织机构信息
        queryMember.setMemberId(member.getMemberId());
        List<UpmsOrg> powerAllOrgList = upmsOrgMapper.selectOrgListJoinOrgMember(new QueryRelationVO(null, queryMember).toMap());

        Set<UpmsRole> powerAllRoleSet = new HashSet<>();
        // 查询该成员的所拥有的角色信息-根据单独授权角色
        UpmsMember queryMemberRole = new UpmsMember();
        queryMemberRole.setMemberId(member.getMemberId());
        List<UpmsRole> memberRoleList = upmsRoleMapper.selectRoleListJoinRoleMember(new QueryVO<>(queryMemberRole).toMap());
        powerAllRoleSet.addAll(memberRoleList);

        // 角色组织机构对应Map
        Map<Long, Set<UpmsOrg>> roleOrgMap = new HashMap<>();
        // 查询该成员的所拥有的角色信息-根据所属组织机构授权角色
        for (int j = 0; j < powerAllOrgList.size(); j++) {
            UpmsOrg queryOrgRole = new UpmsOrg();
            queryOrgRole.setOrgId(powerAllOrgList.get(j).getOrgId());
            List<UpmsRole> orgRoleList = upmsRoleMapper.selectRoleListJoinRoleOrg(new QueryVO<>(queryOrgRole).toMap());
            for (int or = 0; or < orgRoleList.size(); or++) {
                if (orgRoleList.get(or).getRoleType().equals(NCConstants.INT_0)) {
                    powerAllRoleSet.add(orgRoleList.get(or));
                } else {
                    if (memberRoleList.contains(orgRoleList.get(or))) {
                        powerAllRoleSet.add(orgRoleList.get(or));
                    }
                }
            }
//            powerAllRoleSet.addAll(orgRoleList);
            for (int r = 0; r < orgRoleList.size(); r++) {
                if (!roleOrgMap.containsKey(orgRoleList.get(r).getRoleId())) {
                    roleOrgMap.put(orgRoleList.get(r).getRoleId(), new HashSet<>());
                }
                roleOrgMap.get(orgRoleList.get(r).getRoleId()).add(powerAllOrgList.get(j));
            }
        }

        loginUser.setRoleOrgMap(new HashMap<>());
        for (Map.Entry<Long, Set<UpmsOrg>> entry : roleOrgMap.entrySet()) {
            if (!loginUser.getRoleOrgMap().containsKey(entry.getKey())) {
                loginUser.getRoleOrgMap().put(entry.getKey(), new ArrayList<>());
            }
            loginUser.getRoleOrgMap().get(entry.getKey()).addAll(entry.getValue().stream()
                    .map(item -> new IdName(item.getOrgId(), item.getOrgName()))
                    .collect(Collectors.toList()));
        }

        List<UpmsRole> powerAllRoleList = new ArrayList<>(powerAllRoleSet);

        loginUser.setRoleList(powerAllRoleList.stream()
                .map(item -> new IdName(item.getRoleId(), item.getRoleName()))
                .collect(Collectors.toList()));

        boolean hasDefaultRole = false;
        for (int i = 0; i < powerAllRoleList.size(); i++) {
            if (powerAllRoleList.get(i).getRoleId().equals(member.getDefaultRoleId())) {
                hasDefaultRole = true;
            }
        }
        if (!hasDefaultRole && powerAllRoleList.size() > 0) {
            member.setDefaultRoleId(powerAllRoleList.get(0).getRoleId());
        }

        // 授权的组织机构
        List<UpmsOrg> powerOrgList = new ArrayList<>();

        // 授权的角色列表
        Set<UpmsRole> powerRoleSet = new HashSet<>();
        // 判断成员是否开启 是否全角色权限 功能
        if (NCConstants.INT_1.equals(member.getShowAllRole())) {
            // 查询该成员的所拥有的角色信息-根据所属组织机构授权角色
            if (NCConstants.INT_1.equals(member.getShowAllOrg())) {
                powerOrgList.addAll(powerAllOrgList);
                powerRoleSet.addAll(memberRoleList);
                powerRoleSet.addAll(powerAllRoleSet);
            } else {
                powerOrgList.add(org);
                UpmsOrg queryOrgRole = new UpmsOrg();
                queryOrgRole.setOrgId(member.getDefaultOrgId());
                List<UpmsRole> orgRoleList = upmsRoleMapper.selectRoleListJoinRoleOrg(new QueryVO<>(queryOrgRole).toMap());
                powerRoleSet.addAll(orgRoleList);
            }
        } else {
            // 查询该成员的默认绑定角色信息
            powerRoleSet.add(upmsRoleMapper.selectByPrimaryKey(member.getDefaultRoleId()));

            // 查询该角色下授权的组织机构
            UpmsRole queryRole = new UpmsRole();
            queryRole.setRoleId(role.getRoleId());
            powerOrgList = upmsOrgMapper.selectOrgListJoinRoleOrg(new QueryVO<>(queryRole).toMap());
            List<UpmsOrg> endOrgList = new ArrayList<>();
            for (int i = 0; i < powerOrgList.size(); i++) {
                for (int j = 0; j < powerAllOrgList.size(); j++) {
                    if (powerOrgList.get(i).getOrgId() == powerAllOrgList.get(j).getOrgId()) {
                        endOrgList.add(powerOrgList.get(i));
                    }
                }
            }
            powerAllOrgList = endOrgList;
            powerOrgList = endOrgList;
        }

        loginUser.setOrgList(powerAllOrgList.stream()
                .map(item -> new IdName(item.getOrgId(), item.getOrgName()))
                .collect(Collectors.toList()));

        // 所有授权的角色
        List<UpmsRole> powerRoleList = new ArrayList<>(powerRoleSet);

        // 所有授权的菜单
        Set<UpmsMenu> powerMenuSet = new HashSet<>();

        // 设置菜单数据权限，重复的菜单数据权限以最高的为准
        Map<String, Integer> menuDataPowerMap = new HashMap<>();
        Map<String, Set<UpmsRole>> apiRoleMap = new HashMap<>();
        for (int j = 0; j < powerRoleList.size(); j++) {
            UpmsRole roleItem = powerRoleList.get(j);
            UpmsRole query = new UpmsRole();
            query.setTenantId(member.getTenantId());
            query.setRoleId(roleItem.getRoleId());
            query.setRoleSource(NCConstants.INT_1);
            List<UpmsMenu> menuList = roleMenuService.getMenuListByRoleId(query);
            powerMenuSet.addAll(menuList);
            for (int k = 0; k < menuList.size(); k++) {
                // 设置按钮资源数据权限
                if (NCConstants.INT_2 <= menuList.get(k).getMenuType()) {
                    String menuUrlKey = menuList.get(k).getApplicationName() + menuList.get(k).getApiUrl();
                    if (menuDataPowerMap.containsKey(menuUrlKey)) {
                        if (menuDataPowerMap.get(menuUrlKey).compareTo(roleItem.getDataPower()) > 0) {
                            menuDataPowerMap.put(menuUrlKey, roleItem.getDataPower());
                        }
                    } else {
                        menuDataPowerMap.put(menuUrlKey, roleItem.getDataPower());
                    }
                    if (!apiRoleMap.containsKey(menuUrlKey)) {
                        apiRoleMap.put(menuUrlKey, new HashSet<>());
                    }
                    apiRoleMap.get(menuUrlKey).add(roleItem);
                }
            }
        }

        // 设置菜单树
        loginUser.setMenuTree(MenuTreeVO.getMenuTree(new ArrayList<>(powerMenuSet)));

        // 查询该租户所有的组织机构信息
        List<UpmsOrg> allOrgList = orgService.getOrgListCacheByTenantId(tenantId);
        List<UpmsOrg> allOrgListCopy = new ArrayList<>(allOrgList);
        // 查询处理 showAllRole 为 0 不开启 状态下 成员的数据权限
        DataPower dataPower = initDatePower(allOrgList, powerOrgList, loginUser.getOrgId());
        dataPower.setTenantId(tenantId);
        dataPower.setMemberId(member.getMemberId());
        dataPower.setOrgId(loginUser.getOrgId());
        dataPower.setMenuDataPower(menuDataPowerMap);


        // 设置处理 showAllRole 为 1 开启情况下的数据权限
        // 已经处理过的角色信息
        Map<Long, Boolean> handleLong = new HashMap<>();
        Map<String, Set<Long>> apiRolePowerMap = new HashMap<>(roleOrgMap.size());
        Map<Long, Set<Long>> roleOrgPowerMap = new HashMap<>(roleOrgMap.size());
        for (Map.Entry<String, Set<UpmsRole>> entry : apiRoleMap.entrySet()) {
            apiRolePowerMap.put(entry.getKey(), new HashSet<>());
            List<UpmsRole> roleList = new ArrayList<>(entry.getValue());
            List<UpmsOrg> orgList = new ArrayList<>();
            for (int r = 0; r < roleList.size(); r++) {
                apiRolePowerMap.get(entry.getKey()).add(roleList.get(r).getRoleId());
                UpmsRole rolePower = roleList.get(r);
                Set<UpmsOrg> orgSet = roleOrgMap.get(rolePower.getRoleId());
                if (orgSet != null) {
                    orgList.addAll(orgSet);
                }
            }
            for (int r = 0; r < roleList.size(); r++) {
                apiRolePowerMap.get(entry.getKey()).add(roleList.get(r).getRoleId());
                UpmsRole rolePower = roleList.get(r);
                if (!handleLong.containsKey(rolePower.getRoleId())) {
                    DataPower roleDataPower = initDatePower(new ArrayList<>(allOrgListCopy), orgList, loginUser.getOrgId());
                    roleDataPower.setTenantId(tenantId);
                    roleDataPower.setMemberId(member.getMemberId());
                    roleDataPower.setOrgId(loginUser.getOrgId());
                    roleDataPower.setMenuDataPower(menuDataPowerMap);
                    ApiDataPower apiDataPower = roleDataPower.getApiDataPower(entry.getKey(), 0);

                    if (apiDataPower.getOrgList() == null) {
                        // 为null，可以操作租户下所有组织机构数据
                        roleOrgPowerMap.put(rolePower.getRoleId(), null);
                    } else if (apiDataPower.getOrgList().isEmpty()) {
                        // 为空, 只能操作当前登陆人的数据，userId必填
                        roleOrgPowerMap.put(rolePower.getRoleId(), new HashSet<>());
                    } else {
                        roleOrgPowerMap.put(rolePower.getRoleId(), new HashSet<>(apiDataPower.getOrgList()));
                    }
                    handleLong.put(rolePower.getRoleId(), true);
                }
            }
        }

        // 设置接口对应角色
        dataPower.setApiRoleMap(apiRolePowerMap);

        // 设置角色对应组织机构数据
        dataPower.setRoleOrgMap(roleOrgPowerMap);

        // 设置数据权限
        loginUser.setDataPower(dataPower);
    }

    private DataPower initDatePower(List<UpmsOrg> allOrgList, List<UpmsOrg> powerOrgList, Long orgId) {
        Long defaultOrgId = null;
        for (int i = 0; i < powerOrgList.size(); i++) {
            if (powerOrgList.get(i).getOrgId().equals(orgId)) {
                defaultOrgId = orgId;
            }
        }

        // 查询处理 showAllRole 为 0 不开启 状态下 成员的数据权限
        DataPower dataPower = new DataPower();
        dataPower.setOrgId(defaultOrgId);
        dataPower.setDataPower1Orgs(new HashSet<>());
        dataPower.setDataPower2Orgs(new HashSet<>());
        dataPower.setDataPower3Orgs(new HashSet<>());
        dataPower.setDataPower4Orgs(new HashSet<>());

        // 计算七级权限各自对应的机构数据

        // 设置 数据权限3 可以操作所属机构的数据
        powerOrgList.forEach(item -> dataPower.getDataPower3Orgs().add(item.getOrgId()));

        dataPower.getDataPower1Orgs().addAll(dataPower.getDataPower3Orgs());
        // 设置 数据权限4 可以操作当前机构及下级所有机构数据
        if (defaultOrgId != null) {
            dataPower.getDataPower4Orgs().add(defaultOrgId);
        }
        int i = 1;
        while (i != 0) {
            i = initDatePower4(allOrgList, dataPower);
        }
        // 设置 数据权限1 可以操作所属机构及下级机构所有数据
        i = 1;
        while (i != 0) {
            i = initDatePower1(allOrgList, dataPower);
        }
        // 设置 数据权限2 可以操作所属机构及当前机构所有下级机构数据
        dataPower.getDataPower2Orgs().addAll(dataPower.getDataPower4Orgs());
        dataPower.getDataPower2Orgs().addAll(dataPower.getDataPower3Orgs());
        return dataPower;
    }

    /**
     * 初始化数据权限4 可以操作当前机构及下级所有机构数据
     *
     * @param allOrgs
     * @param dataPower
     * @return
     */
    private int initDatePower4(List<UpmsOrg> allOrgs, DataPower dataPower) {
        Iterator<UpmsOrg> orgIterator = allOrgs.iterator();
        int i = 0;
        while (orgIterator.hasNext()) {
            UpmsOrg item = orgIterator.next();
            if (dataPower.getDataPower4Orgs().contains(item.getParentId())) {
                // 查询当前组织机构的所有下级所属机构
                dataPower.getDataPower4Orgs().add(item.getOrgId());
                dataPower.getDataPower1Orgs().add(item.getOrgId());
                orgIterator.remove();
                i++;
            }
        }
        return i;
    }

    /**
     * 初始化数据权限1 可以操作所属机构及下级机构所有数据
     *
     * @param allOrgs
     * @param dataPower
     * @return
     */
    private int initDatePower1(List<UpmsOrg> allOrgs, DataPower dataPower) {
        Iterator<UpmsOrg> orgIterator = allOrgs.iterator();
        int i = 0;
        while (orgIterator.hasNext()) {
            UpmsOrg item = orgIterator.next();
            // 移除已经添加过的所属机构信息
            if (dataPower.getDataPower3Orgs().contains(item.getOrgId())) {
                orgIterator.remove();
                i++;
            } else if (dataPower.getDataPower1Orgs().contains(item.getParentId())) {
                dataPower.getDataPower1Orgs().add(item.getOrgId());
                orgIterator.remove();
                i++;
            }
        }
        return i;
    }
}
